#include "Channel.h"
#include "EventLoop.h"
#include <sys/poll.h>

const int Channel::kNoneEvent = 0;
const int Channel::kReadEvent = POLLIN | POLLPRI;
const int Channel::kWriteEvent = POLLOUT;

Channel::Channel(EventLoop *loop, int fd)
: _loop(loop)
, _fd(fd)
, _events(0)
, _revents(0)
, _index(-1)
, _eventHandling(false)
{
}
void Channel::update()
{
    _loop->updateChannel(this);
}

void Channel::handleEvent(Timestamp receiveTime)
{
    _eventHandling = true;
    if(_revents & POLLNVAL)
    {
        std::cerr << "Channel::handleEvent POLLNVAL\n";
    }

    if((_revents & POLLHUP) && !(_revents & POLLIN))
    {
        std::cerr << "Channel::handleEvent POLLHUP\n";
        if(_readCallback) _closeCallback();
    }
    if(_revents & (POLLERR | POLLNVAL))
    {
        if(_errorCallback) _errorCallback();
    }
    if(_revents & (POLLIN | POLLPRI | POLLHUP))
    {
        if(_readCallback) _readCallback(receiveTime);
    }
    if(_revents & POLLOUT)
    {
        if(_writeCallback) _writeCallback();
    }
}
void Channel::remove()
{
    assert(isNoneEvent());

    // _loop->removeChannel(this);
}